package com.example.feature;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//同 thenCombine 类似  只是这个执行之后没有返回结果
public class ThenAcceptBothDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        //异步任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1:" + Thread.currentThread().getName());
            return "hello";
        }, executorService);
        //异步任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(200L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future2:" + Thread.currentThread().getName());
            return "hello2";
        }, executorService);

        //任务1 连接任务2  同时传递 两个任务的返回值作为参数传递

        future1.thenAcceptBothAsync(future2, (r1, r2) -> {
            System.out.println("combine future3:" + Thread.currentThread().getName());
            System.out.println(r1 + r2 + " no res");
        }, executorService);

        //thenAfterBothAsync  不需要前面两个执行的结果，直接执行
        future1.runAfterBothAsync(future2, ()->{
            System.out.println("runAfterBothAsync:" + Thread.currentThread().getName());
        });
        //applyToEitherAsync 接收先执行完结果，再返回
        CompletableFuture<String> eitherAsync = future1.applyToEitherAsync(future2, (value) -> {
            System.out.println("applyToEither:" + Thread.currentThread().getName());
            return value + " abc";
        }, executorService);

        System.out.println(eitherAsync.get());

        executorService.shutdown();

    }

}
